/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年10月19日
 */
package com.massyframework.beanskin.scriptengine.beancontext.provider;

import javax.script.ScriptEngine;

import com.massyframework.beanskin.assembly.handling.ActivationHandler;
import com.massyframework.beanskin.assembly.handling.HandlerBase;
import com.massyframework.beanskin.assembly.handling.HandlerRegistration;
import com.massyframework.beanskin.scriptengine.beancontext.ScriptEngineAssemblyContext;
import com.massyframework.beanskin.scriptengine.beancontext.ScriptEngineContextAdapter;

/**
 * @author huangkh
 *
 */
class ScriptEngineContextInitalizer extends HandlerBase 
	implements ActivationHandler{

	private volatile HandlerRegistration<ScriptEngineAssemblyContext> registraton;
	
	/**
	 * 
	 */
	public ScriptEngineContextInitalizer() {
		
	}

	@Override
	public void doStarting() throws Exception {
		if (this.registraton == null) {
			ScriptEngineAssemblyContext context =
					new ScriptEngineAssemblyContext();
			this.registraton = this.getLifecycleManager().register(context);
		}
	}

	@Override
	public void doStopped() throws Exception {
		if (this.registraton != null) {			
			this.registraton.unregister();
			this.registraton = null;
		}
	}
	
	/**
	 * 脚本引擎
	 * @return {@link ScriptEngine},可能返回null.
	 */
	protected ScriptEngine getScriptEngine() {
		if (this.registraton == null) {
			return null;
		}
		
		ScriptEngineAssemblyContext context =
				this.registraton.getHandler();
		ScriptEngineContextAdapter beanContext = 
				context.getScriptEngineContextAdapter();
		return beanContext == null ? null: beanContext.getScriptEngine();
	}
	
	/**
	 * 判断脚本对象是否为函数
	 * @param scriptObject {@link Object}
	 * @return {@link boolean},返回{@code true}表示是，否则返回{@code false}
	 */
	protected boolean isFunction(Object scriptObject) {
		if (scriptObject == null) return false;
		if (this.registraton == null) {
			return false;
		}
		
		ScriptEngineAssemblyContext context =
				this.registraton.getHandler();
		ScriptEngineContextAdapter beanContext = 
				context.getScriptEngineContextAdapter();
		return beanContext == null ? false: beanContext.isFunction(scriptObject.getClass());
	}

}
